import moment from 'moment';
import { queryOtaFiles, uploadOtaFile } from '../services/api';
import update from 'immutability-helper';


function method(str, a, b) {
    let type = 'string';
    if (str === 'updateTime') {
        type = 'date';
    } else if (str === 'progId') {
        type = 'num';
    }
    switch (type) {
        case 'num': // 数字排序
            return a - b;
        case 'date': // 日期排序，IE8下'2012-12-12'这种格式无法设置时间，替换成'/'
            return moment(a).unix() - moment(b).unix();
        default:
            // 字符串排序
            return a.localeCompare(b);
    }
}

export default {
    namespace: 'devupdate',

    state: {
        list: [],
        detail: '',
        pagination: {
            current: 1,
            pageSize: 10,
        },
    },

    effects: {
        *fetch({ payload }, { call, put }) {
            const response = yield call(queryOtaFiles, payload);
            let dataSource = response.devOtaFiles;

            let pageSize = 10;
            if (payload.pageSize) {
                pageSize = payload.pageSize * 1;
            }

            const result = {
                list: Array.isArray(response.devOtaFiles) ? dataSource : [],
                pagination: {
                    total: response.pageInfo.pageTotal,
                    pageSize,
                    current: parseInt(payload.page, 10) || 1,
                },
            };

            //console.log('log', result);
            yield put({
                type: 'save',
                payload: result,
            });
        },

        *uploadfile({ payload, callback }, { call, put }) {
            let response = yield call(uploadOtaFile, payload);
            //const response = yield call(uploadTraffic, payload);
            if (response ?.result ?.code === 2001) {
                message.error('上传OTA文件出错，请检查');
            } else {
                yield put({
                    type: 'uploadOtaFile',
                    payload: response.uploadOtaFile,
                });
                if (callback) callback();
            }
        },

    },

    reducers: {
        save(state, action) {
            return {
                ...state,
                list: action.payload.list,
                pagination: action.payload.pagination,
            };
        },

        uploadOtaFile(state, action) {
            const newState = update(state, {
                list: {
                    $splice: [[0, 0, action.payload]],
                },
            });
            return newState;
        },
    },
};
